<template>
  <div class="editor">
    <div class="title item">
      <div class="text">请输入标题:</div>
      <div class="input">
        <Input v-model="title" />
      </div>
    </div>
    <div class="type item">
      <div class="text">
        文章类型:
      </div>
      <div class="input">
        <Cascader :options="options" v-model="type" />
      </div>
    </div>
    <mavon-editor
      v-model="content"
      ref="md"
      @change="change"
      @imgAdd="addImg"
      style="min-height: 600px"
    />
    <div class="btn">
      <Button @click="submit">
        提交
      </Button>
    </div>
  </div>
</template>

<script>
import { Input, Cascader, Message, Button } from "element-ui";
import { mapActions, mapGetters } from "vuex";
import { upload } from "../../api/index"
export default {
  data() {
    return {
      content: "",
      html: "",
      title: "",
      type: []
    };
  },
  methods: {
    ...mapActions(["publish"]),
    addImg(pos, file) {
        const formdata = new FormData()
        formdata.append('image', file);
        const that = this.$refs.md
        upload({
          success(res) {
            console.log(res, "upload success");
            console.log(that.$img2Url(pos, res.src[0]))
          },
          fail(err) {
            console.log(err);
          },
          data: formdata
        })
    },
    change(value, render) {
      // render 为 markdown 解析后的结果[html]
      this.html = render;
    },
    submit() {
      const createdAt = new Date().getTime().toString();
      const isPass =
        this.isLogin &&
        this.type.length === 1 &&
        this.title.length > 1 &&
        this.content.length > 1;
      if (isPass) {
        this.publish({
          token: this.token,
          typeID: this.type[0],
          title: this.title,
          content: this.html,
          createdAt
        })
          .then(() => {
            this.$router.push("/");
          })
          .catch(() => {
            Message("上传失败");
          });
      } else {
        Message("请在检查一遍");
      }
    }
  },
  computed: {
    ...mapGetters(["token", "types", "isLogin"]),
    options() {
      return this.types.map(item => {
        return {
          label: item.type,
          value: item.id
        }
      });
    }
  },
  components: {
    Input,
    Cascader,
    Button
  }
};
</script>

<style scoped>
.editor {
  width: 100%;
}
.item {
  display: flex;
}
.item .text {
  width: 100px;
  font-size: 16px;
  color: #ffffff;
}
.item .input {
  max-width: 400px;
}
.type {
  margin: 20px 0;
}
</style>
